using GameFramework.Battle.Core;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using Yoozoo.Libs;

namespace Gameplay.PVE
{
    public class BehaviorComponent : IComponent
    {
        private BehaviorTree behaviorTree;
        private UnitBase unit;
        
        void IClass.OnReset()
        {
            behaviorTree = null;
        }

        void IComponent.OnInitialize(UnitBase unit)
        {
            this.unit = unit;
        }
        
        public void Update()
        {
            ((IComponent) this).OnUpdate();
        }
        
        public void Initialize(UnitBase unit)
        {
            ((IComponent)this).OnInitialize(unit);
        }

        public void Birth()
        {
            ((IComponent)this).OnBirth();
        }

        void IComponent.OnUpdate()
        {
            if (unit.Data.isDead)
            {
                return;
            }
            if (unit.Data.lockTarget != null && unit.Data.lockTarget.Data.isDead)
            {
                unit.Data.SetLockTarget(null);
            }
            behaviorTree?.Update();
        }

        void IComponent.OnBirth()
        {
            behaviorTree = new BehaviorTree();
            if (unit.Data.unitType == 1)
            {
                behaviorTree.Initialize(PveUtils.GetMortalBehaviorData());
            }
            else if (unit.Data.unitType == 0)
            {
                behaviorTree.Initialize(PveUtils.GetTestBehaviorData());
            }
            else if (unit.Data.unitType == 2)
            {
                behaviorTree.Initialize(PveUtils.GetVehicleBehaviorData());
            }
            behaviorTree.SetVariable(ESharedVariablesType.Executor, unit);
        }

        void IComponent.OnDead()
        {
            //behaviorTree = null;
        }
        
        public void Dispose()
        {
            ((IClass)this).OnReset();
        }
    }
}